import $ from 'jquery'
import eleData from '../utils/RichElement.js'
import eleOper from '../utils/ElementOperator.js'
import chinase from '../utils/ChineseWord.js'
import { ElMessage } from 'element-plus';

const title2 = ['h1', 'h2', 'h3', 'h4', 'h5'];

const olList = ['ul', 'ol'];

// 普通的粘贴
const commonPaste = 'common';

// 从idea中复制过来的
const ideaCodePaste = 'ideaCode';

// 列表信息
const orderOl = "listOrder";

const blankTwo = "&nbsp;&nbsp;&nbsp;&nbsp;";

const basteRevole = {
	saveElement(element) {
		if (element == null || element == undefined || element == '' || element == 'null') {
			return;
		}
		eleOper.insertDom(element);
	},
	imageToBase64(img) {
		let canvas = document.createElement('canvas');
		canvas.width = img.width;
		canvas.height = img.height;
		let ctx = canvas.getContext("2d");
		ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
		return canvas.toDataURL();
	},
	downImg(imgDom) {
		let src = $(imgDom).attr('src');
		if (src.indexOf('http') == 0 || src.indexOf('ftp') == 0) {
			let image = new Image();
			image.src = src;
			image.onload = () => {
				let base64 = basteRevole.imageToBase64(image);
				eleOper.insertNode(base64, eleData.image, true);
			}
			image.onerror = (e) => {
				console.log(e);
				ElMessage.error("图片加载失败")
			}
		} else {
			eleOper.insertNode(src, eleData.image, true);
		}
	},
	dealItemImg(dom) {
		let children = dom.childNodes;
		for(let i = 0; i < children.length; i++) {
			let d = children[i]
			if (!d.tagName) {
				eleOper.insertNode($(d).text(), eleData.content);
				continue;
			}
			let tag = d.tagName.toLowerCase();
			if (tag == 'img') {
				basteRevole.downImg(d)
			} else {
				eleOper.insertNode($(d).text(), eleData.content);
			}
		}
	},
	common (dom) {
		let chinaseWord = null;
		let len = dom.length;
		for(let i = 0; i < len; i ++) {
		   if(dom[i].tagName == undefined) continue;
		   let d = dom[i]
		   let tag = d.tagName.toLowerCase();
		   let idTag = $(d).attr("tag")
		   if (tag == 'img' && idTag != eleData.image.id) {
			   basteRevole.downImg(dom[i])
			   continue;
		   }
		   if (idTag != eleData.chineseWord.id && idTag != eleData.code.id 
		   && idTag != eleData.content.id && idTag != eleData.header.id 
		   && idTag != eleData.image.id && idTag != eleData.listOrder.id 
		   && idTag != eleData.title1.id && idTag != eleData.title2.id 
		   && idTag != eleData.chineseWord.wordId && idTag != eleData.chineseWord.pingyinId) {
				let children = dom[i].querySelectorAll('img');
				if (children.length != 0) {
					basteRevole.dealItemImg(dom[i]);
				}
		   }
		   if (idTag == eleData.chineseWord.id || idTag == eleData.code.id 
		   || idTag == eleData.content.id || idTag == eleData.header.id 
		   || idTag == eleData.image.id || idTag == eleData.listOrder.id 
		   || idTag == eleData.title1.id || idTag == eleData.title2.id) {
			   eleOper.insertDom(d);
			   basteRevole.saveElement(chinaseWord)
			   chinaseWord = null;
		   } else if (idTag == eleData.chineseWord.wordId) {
			   if (chinaseWord == null) {
				   chinaseWord = eleOper.createElementNoParent(eleData.chineseWord);
				   chinaseWord.innerHTML = ''
			   }
			   $(chinaseWord).append(d);
		   } else if ((i + 1) < len && $(d).attr("tag") == eleData.chineseWord.pingyinId 
				&& $(dom[i + 1]).attr("tag") == eleData.chineseWord.contentId) {
			   eleOper.createELementChinase(d, dom[i+1]);
			   i ++;
		   } else if ('h1' == tag) {
			   eleOper.insertNode($(dom[i]).text(), eleData.title1);
			   basteRevole.saveElement(chinaseWord)
			   chinaseWord = null;
		   } else if (title2.indexOf(tag) != -1) {
			   eleOper.insertNode($(dom[i]).text(), eleData.title2);
			   basteRevole.saveElement(chinaseWord)
			   chinaseWord = null;
		   } else if (olList.indexOf(tag) != -1) {
			   let children = $(dom[i]).children();
			   for(let j =0; j < children.length; j ++) {
				   if (j == 0) {
					   eleOper.insertOlWdinwo(eleData.listOrder, $(children[j]).text());
				   } else {
					   eleOper.insertCode(eleData.listOrder, $(children[j]).text());
				   }
			   }
			   basteRevole.saveElement(chinaseWord)
			   chinaseWord = null;
		   } else {
			   eleOper.insertNode($(dom[i]).text(), eleData.content);
			   basteRevole.saveElement(chinaseWord)
			   chinaseWord = null;
		   }
		}
		basteRevole.saveElement(chinaseWord)
	},
	isBr(dom) {
		let children = $(dom).children();
		for(let i = 0; i < children.length; i++) {
			if (children[i].tagName.toLowerCase() == 'br') return true;
		}
		return false;
	},
	ideaCodePaste (dom, node) {
		for (let i = 0; i < dom.length; i++) {
			// if ('div' != dom[i].tagName.toLowerCase()) continue;
			let children = dom[i].childNodes;
			// debugger;
			let content = "";
			let indent = 0;
			for(let j = 0; j < children.length; j ++) {
				if (children[j].tagName == null || children[j].tagName == undefined || children[j].tagName == '') {
					content += $(children[j]).text();
				} else {
					if (children[j].tagName.toLowerCase() == 'br') {
						if (content.indexOf("}") != -1) indent = indent - 2;
						content = content.replaceAll('<', '&lt;');
						content = content.replaceAll('>', '&gt;');
						node = eleOper.createCodeItem(node, content, true);
						$(node).css({"text-indent": indent + "em"});
						$(node).attr("indent", indent);
						// eleOper.insertCode(eleData.code, content);
						if (content.indexOf("{") != -1) indent += 2;
						content = "";
						continue;
					}
					if (children[j].tagName.toLowerCase() == 'span') {
						content += $(children[j]).text();
						if (basteRevole.isBr(children[j])) {
							if (content.indexOf("}") != -1) indent -= 2;
							content = content.replaceAll('<', '&lt;');
							content = content.replaceAll('>', '&gt;');
							node = eleOper.createCodeItem(node, content, true);
							$(node).css({"text-indent": indent + "em"});
							$(node).attr("indent", indent);
							// eleOper.insertCode(eleData.code, content);
							if (content.indexOf("{") != -1) indent += 2;
							content = "";
							continue;
						}
					}
				}
			}
			if (content != "") {
				content = content.replaceAll('<', '&lt;');
				content = content.replaceAll('>', '&gt;');
				node = eleOper.createCodeItem(node, content, true);
				if (content.indexOf("}") != -1) indent -= 2;
				$(node).css({"text-indent": indent + "em"});
				$(node).attr("indent", indent);
				// eleOper.insertCode(eleData.code, content);
			}
		}
	},
	orderOl(dom) {},
	imageDeal(file) {
		if (file !== null) {
			let blob = new Blob([file], { type: 'image/png' || 'application/*' });
			let reader = new FileReader();
			reader.readAsDataURL(file);
			reader.onload = function() {
			  let imgResult = reader.result;
			  eleOper.insertNode(imgResult, eleData.image, true);
			};
		}
	}, 
	commonText(text) {
		eleOper.insertContent(text);
	},
	main (clipboardData, event, type = 'common') {
		// for chrome
		var items = clipboardData.items, len = items.length, file = null
		//阻止默认行为即不让剪贴板内容在div中显示出来
		event.preventDefault()
		//在items里找粘贴的image,据上面分析,需要循环
		let node = eleOper.getSelectNode();
		let tag = $(node).attr('tag');
		if (tag == 'body' || tag == 'title' || tag == eleData.code.id || tag == eleData.code.childId) {
			type = ideaCodePaste;
		}
		let html = null;
		let text = null;
		for (var i = 0; i < len; i++) {
			let mimeType = items[i].type;
			if (mimeType.indexOf('image') !== -1) {
				file = items[i].getAsFile()
			} else if (mimeType.indexOf('text/html') !== -1) {
			   html = (event.clipboardData || window.clipboardData).getData('text/html');
			   // console.log(paste)
			   
			} else if (mimeType.indexOf('text/plain') !== -1) {
				text = (event.clipboardData || window.clipboardData).getData('text/plain');
			}
		}
		if (html != null) {
			let dom = $(html);
			if (type == commonPaste) {
			   basteRevole.common(dom);
			} else if (type == ideaCodePaste) {
			   basteRevole.ideaCodePaste(dom, node);
			} else if (type == orderOl) {
			   basteRevole.orderOl(dom);
			}
		} else if (text != null) {
			basteRevole.commonText(text);
		}
		basteRevole.imageDeal(file);
	}
}

export default basteRevole;